//
//  WashMapViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/9/7.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "WashMapViewController.h"

#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>

#import "JJAnnotation.h"
#import "MyAnnoModel.h"
#import "WashCarViewController.h"
@interface WashMapViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate>{
    BMKMapView *_mapView;
    BMKLocationService *location;
    BMKGeoCodeSearch *geocodeSearch;
    CGFloat lat;
    CGFloat lng;
    BMKPoiSearch *poisearch;
    NSMutableArray *array;
    
    UIView *footerview;//尾视图
    UIButton *imgBtn;
    CLLocationCoordinate2D coor2d;
    
    JJAnnotation *jjano;
    UIImageView *imageView;
    UILabel *labTit;
    UILabel *labPlace;
    UILabel *labKM;
    UIView  *views;
    NSDictionary *dic;
}

@property (nonatomic,strong)NSMutableArray *datas;

@end

@implementation WashMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    
    [self loadUI];
    array = [NSMutableArray array];
    _datas = [NSMutableArray array];
    [self loadMap];
    //[self loadData];
    
}

- (void)loadUI{
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    _mapView.delegate = self;
    [_mapView setZoomEnabled:YES];
    [_mapView setZoomLevel:14];//设置级别
    [self.view addSubview:_mapView];
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(30, 30, 28, 28);
    [btn setImage:[UIImage imageNamed:@"箭头3"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    //
    footerview = [[UIView alloc] initWithFrame:CGRectMake(10, ScreenHeight-120, ScreenWidth-20, 90)];
    footerview.backgroundColor = [UIColor whiteColor];
    footerview.hidden = YES;
    [self.view addSubview:footerview];
    
    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 90, 70)];
    [imageView sd_setImageWithURL:[NSURL URLWithString:@""] placeholderImage:[UIImage imageNamed:@"timg22"]];
    [footerview addSubview:imageView];
    
    labTit = [[UILabel alloc] init];
    labTit.text = @"";
    labTit.font = [UIFont boldSystemFontOfSize:15.0];
    [footerview addSubview:labTit];
    [labTit makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.right).offset(8);
        make.top.equalTo(imageView.top);
    }];
    
    labPlace = [[UILabel alloc] init];
    labPlace.text = @"";
    labPlace.textColor = [UIColor darkGrayColor];
    labPlace.font = [UIFont systemFontOfSize:12.0];
    [footerview addSubview:labPlace];
    [labPlace makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.right).offset(8);
        make.centerY.equalTo(imageView.centerY);
    }];
    
    views = [[UIView alloc] init];
    [footerview addSubview:views];
    [views makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(labPlace.left);
        make.bottom.equalTo(imageView.bottom);
        make.width.equalTo(100);
        make.height.equalTo(20);
    }];
    
    UIImageView *image2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"导航-(1)"]];
    [footerview addSubview:image2];
    [image2 makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(footerview.right).offset(-8);
        make.bottom.equalTo(imageView.bottom);
        make.width.height.equalTo(20);
    }];
    
    labKM = [[UILabel alloc] init];
    labKM.text = @"2.4km";
    labKM.font = [UIFont boldSystemFontOfSize:12.0];
    [footerview addSubview:labKM];
    [labKM makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(image2.left);
        make.bottom.equalTo(image2.bottom);
    }];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickDet)];
    footerview.userInteractionEnabled = YES;
    [footerview addGestureRecognizer:tap];
    
}

- (void)setIsShowBottomView:(NSString *)isShowBottomView{
    _isShowBottomView = isShowBottomView;
    footerview.hidden = NO;
}

- (void)clickDet{
    WashCarViewController *car = [[WashCarViewController alloc] init];
    NSString *merid = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"id"] integerValue]];
    car.merId = merid;
    car.name = [dic objectForKey:@"name"];
    car.place = [NSString stringWithFormat:@"地址:%@",[dic objectForKey:@"suite"]];
    car.count = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"thenumberof"] integerValue]];
    car.start = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"star"] integerValue]];;
    
    NSMutableArray *images = [NSMutableArray array];
    NSString *img = [dic objectForKey:@"img"];
    NSArray *arr = [img  componentsSeparatedByString:@"|"];
    for (NSString *str in arr) {
        NSString *aaaa = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],str];
        [images addObject:aaaa];
    }
    car.images = images;
    car.km = [NSString stringWithFormat:@"%@km",[dic objectForKey:@"km"]];
    car.lat = [dic objectForKey:@"latitude"];
    car.lng = [dic objectForKey:@"longitude"];
    [self.navigationController pushViewController:car animated:YES];
}

- (void)loadMap{
    //定位服务
    location = [[BMKLocationService alloc] init];
    //开启定位
    [location startUserLocationService];
    
    //显示定位图层
    _mapView.showsUserLocation = YES;
    
    //自定义精度圈
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    param.accuracyCircleStrokeColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:0.5];
    param.accuracyCircleFillColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.3];
    [_mapView updateLocationViewWithParam:param];
    
    //反编码
    geocodeSearch = [[BMKGeoCodeSearch alloc] init];
    geocodeSearch.delegate = self;
    
}

- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    location.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    location.delegate = nil;
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = userLocation.location.coordinate;
    //
    
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
    _mapView.centerCoordinate = userLocation.location.coordinate;
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    
    [self loadData];
    //
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    
    BOOL flag = [geocodeSearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
        //停止定位
        [location stopUserLocationService];
        
    }else{
        NSLog(@"反geo检索发送失败");
    }
    //停止定位
    [location stopUserLocationService];
}
#pragma - mark BMKGeoCodeSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    NSLog(@"%@---%@---%@--",result.addressDetail,result.address,result.businessCircle);
    
}

-(void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"定位失败!");
}
//洗车-经纬度
- (void)loadData{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    //29.514623 ,,106.522446
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude  forKey:@"latitude"];
    NSLog(@"parmas:%@",parmas);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *url = [NSString stringWithFormat:@"%@/App/CarWash/graticules",urlHead];
    [manager POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"经纬度res:%@",responseObject);
        array = [responseObject objectForKey:@"result"];
        [self loadAnno];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

- (void)sendLocationWithArray:(NSArray *)arrLocation{
    NSMutableArray *arrLo = [NSMutableArray array];
    for (NSDictionary *dic in arrLocation) {
//        NSArray *arr = @[dic[@"longitude"],dic[@"latitude"]];
//        [arrLo addObject:arr];
    }
//    [self loadAnnoShopDetailWithArr:arrLocation];
}


//加载商家
- (void)loadAnno{
    for (NSDictionary *dic in array) {
        MyAnnoModel *model = [[MyAnnoModel alloc] initWithAnnotationModelWithDict:dic];
        
        
        [_datas addObject:model];
        
    }
    [_mapView addAnnotations:_datas];
}

//加载商家
- (void)loadAnnoShopDetailWithArr:(NSArray *)arr{
    NSArray *arrF = arr[0];
    for (NSDictionary *dic in arrF) {
        MyAnnoModel *model = [[MyAnnoModel alloc] initWithAnnotationModelWithDict:dic];
        
        [_datas addObject:model];
        
    }
    [_mapView addAnnotations:_datas];
}


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[JJAnnotation class]]) {
        
        BMKAnnotationView *annoView = [[BMKAnnotationView alloc] init];
        annoView.image = [UIImage imageNamed:@""];
        
        annoView.canShowCallout = YES;
        return annoView;
        
    }
    
    jjano = (JJAnnotation *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"otherAnnotationView"];
    if (!jjano) {
        jjano = [[JJAnnotation alloc] initWithAnnotation:annotation reuseIdentifier:@"otherAnnotationView"];
    }
    
    jjano.image = [UIImage imageNamed:@"店未选中"];
    jjano.imageView.image = [UIImage imageNamed:@"店未选中"];
    
    MyAnnoModel *model = (MyAnnoModel *)annotation;
    
    jjano.dic = model.dic;
    NSString *index = [model.dic objectForKey:@"id"];
    
    jjano.tag = [index integerValue];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click:)];
    jjano.userInteractionEnabled = YES;
    [jjano addGestureRecognizer:tap];
    
    return jjano;
    
}

- (void)click:(id)sender{
    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
    UIView *view = [tap view];
    NSInteger count = view.tag;
    NSString *str = [NSString stringWithFormat:@"%li",count];
    [self loadStr:str];
}

- (void)loadStr:(NSString *)str{
    footerview.hidden = NO;
    NSString *longitude = [NSString stringWithFormat:@"%f",lng];
    NSString *latitude = [NSString stringWithFormat:@"%f",lat];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:str forKey:@"merchantid"];
    [parmas setObject:longitude forKey:@"longitude"];
    [parmas setObject:latitude forKey:@"latitude"];
    NSString *url = [NSString stringWithFormat:@"%@/App/CarWash/merchantdetails",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"aaaares:%@",responseObject);
        dic = [responseObject objectForKey:@"result"];
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[dic objectForKey:@"img"]];
        NSString *name = [dic objectForKey:@"name"];
        NSString *place = [dic objectForKey:@"suite"];
        NSString *count = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"star"] integerValue]];
        NSString *km = [dic objectForKey:@"km"];
        [imageView sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@""]];
        labTit.text = name;
        labPlace.text = place;
        labKM.text = [NSString stringWithFormat:@"%@km",km];
        
        StarView *starView = [[StarView alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
        starView.showStar = [count integerValue] * 20;
        [views addSubview:starView];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)clicks:(UIButton *)btn{
    //[imgBtn setImage:[UIImage imageNamed:@"店"] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
